import datetime
import json
import time

import requests
import websocket
from peewee import SqliteDatabase, Model, CharField, ForeignKeyField, DoubleField, BooleanField, DoesNotExist, DateField
from pip._vendor.distlib import database

try:
    import thread
except ImportError:
    import _thread as thread

wssurl = "wss://so.z6002.com/bet"
# 北京28 玩法 1-3
beji28 = ["51118", "51119", "51120"]

db = SqliteDatabase('pc.db')

CPQH=0
winRate=0.0

class BaseModel(Model):
    class Meta:
        database = db


class Player28(BaseModel):
    name = CharField(unique=True)
    rate = DoubleField()
    total=CharField(default='0')
    activity = DateField(formats='%Y-%m-%d %H:%M')


class Recording(BaseModel):
    user = ForeignKeyField(Player28, backref='recording')
    # 期号
    cpqh = CharField()
    # 内容
    wfmc3 = CharField()
    # 价格
    price = CharField()
    # 是否结算  输为 false 赢为true
    settlement = BooleanField(default=False)



def on_message(ws, message):
    global winRate
    jsonData = json.loads(message)
    wfbm1 = jsonData.get('wfbm1')
    name = jsonData.get('name')
    if name == '游*****客' or name == '' or name is None: return

    if wfbm1 in beji28:
        time_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        message = jsonData.get('message')
        if isinstance(message, list):
            dataRow=[]
            try:
                player = Player28.get(Player28.name == name)
                player.activity = time_date
                player.save()
            except DoesNotExist:
                player = Player28(name=name, rate='0.00', activity=time_date)
                player.save()
            print("当前压的期数:"+str(CPQH))
            for m in message:
                if float(m.get('pl')) >= 30: continue
                wfmc3 = m.get("wfmc3")
                if wfmc3 in ('单', '双', '大', '小', '大单', '小单', '大双', '小双'):

                    dataRow.append({
                       "user":player,
                        "wfmc3": wfmc3,
                        "price": m.get('price'),
                        "cpqh":m.get('cpqh')
                    })
            Recording.insert_many(dataRow).execute()


def kj():
    """
    十秒查看一次
    """
    kjqh = 0
    global  CPQH
    while True:
        time.sleep(3)
        jsonData = lottery()
        CPQH =jsonData.get("CPQH")
        if jsonData.get("CTIME") >10: continue

        print('================看看啦=============================')
        time.sleep(10)

        kj = jsonData.get('KJQH')
        if kjqh == kj:
            continue

        kjqh = kj
        dx = jsonData.get('DX')
        ds = jsonData.get('DS')
        zh = dx + ds
        recordings = Recording.select().where(
            Recording.cpqh == jsonData.get('KJQH'), Recording.settlement == False,
            (Recording.wfmc3 == dx) | (Recording.wfmc3 == dx) | (Recording.wfmc3 == zh)
        )
        for r in recordings:
            r.settlement = True
            r.save()
        rate()


def on_error(ws, error):
    run()


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    create_tables()
    data = """
      {"type":"login","nameid":"9927873","token":"542056d868d54dc4a53f859f3187568a","userType":1}
      """
    ws.send(data)
    thread.start_new_thread(kj, ())


def run():
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(wssurl,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()


def lottery():
    headers = {
        'user-agent': 'Mozilla/5.0',
        'X-Requested-With': 'XMLHttpRequest'
    }
    r = requests.post('https://www-pc44.com/lottery/findCpqhAndTime.do',
                      data={"cpbm": "51"},
                      headers=headers)
    return r.json()


def rate():
    time_date = datetime.datetime.now() - datetime.timedelta(hours=1)
    time_date = time_date.strftime("%Y-%m-%d %H:%M:%S")

    players = Player28.select().where(Player28.activity >= time_date)
    for p in players:
        win = Recording.select().where(Recording.user == p, Recording.settlement == True).count()
        lose = Recording.select().where(Recording.user == p, Recording.settlement == False).count()
        if win != 0:
            p.total = win + lose
            p.rate = win / (win + lose) * 100
            p.save()


def create_tables():
    with db:
        db.create_tables([Player28, Recording])


if __name__ == '__main__':
    # thread.start_new_thread(run, ())
    # create_tables()
    run()
    # rate()
